//
//  YBDestroySureVC.m
//  WuyouTang
//
//  Created by YB007 on 2020/6/22.
//  Copyright © 2020 cat. All rights reserved.
//

#import "YBDestroySureVC.h"
#import <WebKit/WebKit.h>
#import "YBTabBarController.h"
@interface YBDestroySureVC ()<WKNavigationDelegate>
{
    UIView *_shadowView;
}
@property(nonatomic,strong)WKWebView *webView;
@property (nonatomic,strong) CALayer *progresslayer;
@property(nonatomic,strong)UIButton *suerBtn;
@property(nonatomic,strong)UIButton *cancleBtn;
@end

@implementation YBDestroySureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"注销账号");
    
    self.webView = [[WKWebView alloc] init];
    self.webView.navigationDelegate = self;
    _webView.backgroundColor = Normal_Color;
    [self.view addSubview:self.webView];
    self.progresslayer = [[CALayer alloc]init];
    self.progresslayer.frame = CGRectMake(0, 0, _window_width*0.1, 2);
    self.progresslayer.backgroundColor = Pink_Cor.CGColor;
    [self.webView.layer addSublayer:self.progresslayer];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    NSString *url = [h5url stringByAppendingFormat:@"/portal/page/index/?id=151"];
    url = [url stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    
    _shadowView = [[UIView alloc]init];
    _shadowView.backgroundColor = Normal_Color;
    [self.view addSubview:_shadowView];
    
    [self.view addSubview:self.suerBtn];
    [_suerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view.mas_width).multipliedBy(0.4);
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(0.5);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(self.view.mas_bottom).offset(-ShowDiff-20);
    }];
    [self.view addSubview:self.cancleBtn];
    [_cancleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerY.equalTo(_suerBtn);
        make.centerX.equalTo(self.view.mas_centerX).multipliedBy(1.5);
    }];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.equalTo(self.view);
        make.top.equalTo(self.naviView.mas_bottom);
        make.bottom.equalTo(_suerBtn.mas_top).offset(-10);
    }];
    [_shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerY.centerX.equalTo(_webView);
    }];
}

- (UIButton *)suerBtn {
    if (!_suerBtn) {
        _suerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_suerBtn setTitleColor:Pink_Cor forState:0];
        _suerBtn.titleLabel.font = SYS_Font(15);
        [_suerBtn setTitle:YZMsg(@"确认注销") forState:0];
        _suerBtn.layer.cornerRadius = 20;
        _suerBtn.layer.masksToBounds = YES;
        _suerBtn.layer.borderColor = Pink_Cor.CGColor;
        _suerBtn.layer.borderWidth = 1;
        [_suerBtn addTarget:self action:@selector(clikcSureBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _suerBtn;
}
-(void)clikcSureBtn {
    NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),
                                 @"msg":YZMsg(@"点击确认注销后，账号将立即注销"),
                                 @"left":YZMsg(@"取消"),
                                 @"right":YZMsg(@"确认"),
                                 };
    YBWeakSelf;
    YBAlertView *alertView = [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            [weakSelf sureDestroy];
        }
    }];
    [alertView.sureBtn setTitleColor:RGB_COLOR(@"#593FB0", 1) forState:0];
    [alertView.cancleBtn setTitleColor:RGB_COLOR(@"#000000", 1) forState:0];
    
}
- (NSString *)currentTimeStamp {
    NSDate *datenow = [NSDate date];
    NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeStamp;
}
-(void)sureDestroy {
    NSMutableDictionary *mudic = @{
        @"uid":[Config getOwnID],
        @"token":[Config getOwnToken],
        @"time":[self currentTimeStamp],
    }.mutableCopy;
    [mudic setObject:[PublicObj sortString:mudic] forKey:@"sign"];
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:@"Login.cancelAccount" Dic:mudic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
        if (code == 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf quitLogin];
            });
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}

-(void)quitLogin{
    [PublicObj resetUserToVisitor];
    
    YBTabBarController *root = [[YBTabBarController alloc]initWithAlert:NO];
    YBNavigationController *navroot = [[YBNavigationController alloc]initWithRootViewController:root];
    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *app2 = (AppDelegate*)app.delegate;
    [app2.window removeAllSubViews];
    app2.window.rootViewController = navroot;
    
}
- (UIButton *)cancleBtn {
    if (!_cancleBtn) {
        _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancleBtn setTitleColor:RGB_COLOR(@"#ffffff", 1) forState:0];
        _cancleBtn.titleLabel.font = SYS_Font(15);
        [_cancleBtn setTitle:YZMsg(@"取消") forState:0];
        _cancleBtn.backgroundColor = Pink_Cor;
        _cancleBtn.layer.cornerRadius = 20;
        _cancleBtn.layer.masksToBounds = YES;
        [_cancleBtn addTarget:self action:@selector(clikcCancleBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancleBtn;
}
-(void)clikcCancleBtn {
    [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
}

// 观察者
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        float floatNum = [[change objectForKey:@"new"] floatValue];
        self.progresslayer.frame = CGRectMake(0, 0, _window_width*floatNum, 2);
        if (floatNum == 1) {
            __weak __typeof(self)weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.progresslayer.frame = CGRectMake(0, 0, 0, 3);
                _shadowView.hidden = YES;
            });
        }
    }else if ([keyPath isEqualToString:@"title"]){//网页title
        if (object == self.webView){
            self.titleL.text = self.webView.title;
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSString *url = navigationAction.request.URL.absoluteString;
    if (navigationAction.targetFrame.isMainFrame) {
        NSLog(@"target is main ... %@",url);
        if (navigationAction.sourceFrame.mainFrame) {
            NSLog(@"source is main...%@",url);
           
            if ([url containsString:@"tel:"]) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
             
            
        } else {
            NSLog(@"source is not main...%@",url);
        }
    } else {
        NSLog(@"target is not main ... %@",url);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    NSLog(@"在发送请求之前：%@",navigationAction.request.URL.absoluteString);
}


-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];

}

@end
